﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Analyze.Manager;
using log4net;

namespace Analyze.Service
{
    public class SegmentationService
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(SegmentationService));
        /// <summary>
        /// 美团云主机(北京机房43.241.223.121）
        /// 阿里云主机(杭州机房120.26.6.172)
        /// </summary>
        public const string ApiServer = "http://api.pullword.com/get.php";

        private static HttpWebRequest GetRequest(string content,float rank = 1)
        {
            string url = ApiServer + "?" + "source=" + HttpUtility.UrlEncode(content) + "&param2=1&param1="+rank;
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.Method = WebRequestMethods.Http.Get;
            return request;
        }
        
        /// <summary>
        /// BosonNlp 分词服务
        /// </summary>
        /// <param name="contents"></param>
        /// <returns></returns>
        public static List<List<string>> GetWords(string[] contents)
        {
            var words = BosonNlpApi.GetWords(contents);
            for (var i = 0; i < contents.Length; i++)
            {
                List<string> manWords = ManWordManager.GetInstance().GetManWords(contents[i]);
                if (null != manWords)
                {
                    words[i].AddRange(manWords);
                }
            }
            return words;
        }
        
        public static Dictionary<string, float> GetWords(string content)
        {
            var dictionary = new Dictionary<string, float>();

            var manWords = ManWordManager.GetInstance().GetManWords(content);
            
            foreach (string manWord in manWords)
            {
                dictionary.Add(manWord,1);
            }
            
            if (null == content || "".EndsWith(content))
            {
                return dictionary;
            }

            string result = null;
            var request = GetRequest(content);
            try
            {
                HttpWebResponse response = (HttpWebResponse) request.GetResponse();
                Stream stream = response.GetResponseStream();
                stream.ReadTimeout = 5000;
                if (stream != null)
                {
                    StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
                    result = streamReader.ReadToEnd();
                    streamReader?.Close();
                    stream?.Close();
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                return dictionary;
            }
            
            string[] separator = {
                "\r\n"
            };

            char[] sp = {':'};
            
            var strings = result.Split(separator,StringSplitOptions.RemoveEmptyEntries);

            if (strings.Length > 0 && !result.Contains(":"))
            {
                try
                {
                    var responseStream = GetRequest(content, 0.8f).GetResponse().GetResponseStream();
                    responseStream.ReadTimeout = 5000;
                    StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    result = streamReader.ReadToEnd();
                    streamReader?.Close();
                    responseStream?.Close();
                    strings = result.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return dictionary;
                }
                
            }
            
            foreach (var s in strings)
            {
                var split = s.Split(sp);
                var word = split[0];
                
                if (dictionary.ContainsKey(word)) continue;

                if (Regex.IsMatch(word, @".*[0-9].*")) continue;
                    
                float rank = 1f;
                if (split.Length > 1)
                {
                    rank = float.Parse(split[1]);
                }
                dictionary.Add(word, rank);
            }

            return dictionary;
        }
    }
}